import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue'

// 数据懒加载函数
export const useLazyData = (apiFn) => {
  // 监听的对象
  const target = ref(null)
  // 请求的数据
  const result = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        // 调用API请求数据
        apiFn().then(data => {
          result.value = data.result
        })
      }
    }
  )
  return { target, result }
}
